package com.photoeditor.demo.ui.widget.gallery;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.photoeditor.R;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.bean.SeparatorBean;
import com.photoeditor.demo.model.bean.ThumbnailBean;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.ImageManageUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 相册页面一行布局
 */
public class GalleryRowItem extends LinearLayout implements GalleryCellItem.OnItemListener {

    private int mType;

    //类别（Today  This month  year-month）
    public static final int TYPE_SEPARATOR = 1;
    public static final int TYPE_IMAGE = 2;
    public static final int TYPE_AD = 3;

    private int mColNum = 4;

    private SeparatorBean mSeparator;
    private List mListData;

    /**
     * 两张图片之间的间距
     */
    private int mMargin;

    //用于缓存当前计算出来的图片需要显示的宽度
    private int mImageWidth;

    private OperationListener mListener;

    private boolean mCheckStatus;

    private int mPosition;

    private int mSeparatorHeight;

    private static final int DO_NONE = -1;

    //是否是选择图片模式 用于统一video标识
    private boolean mPicMode = false;

    private TextView mSeparatorTextView;
    private ImageView mSeparatorCheckBox;

    public GalleryRowItem(Context context, int colNum) {
        super(context);
        setWillNotDraw(false);
        mColNum = colNum;
        init();
    }

    public GalleryRowItem(Context context) {
        super(context);
        setWillNotDraw(false);
        init();
    }

    public GalleryRowItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        init();
    }

    private void init() {
        Resources res = getResources();
        mMargin = res.getDimensionPixelSize(R.dimen.gallery_distance);
        int margin = res.getDimensionPixelSize(R.dimen.gallery_left_margin);
        mImageWidth = (ImageManageUtil.getScreenWidth() - (mColNum - 1) * mMargin - margin * 2) / mColNum;
        mSeparatorHeight = res.getDimensionPixelOffset(R.dimen.gallery_separator_height);
        mCheckStatus = false;
    }

    public int getType() {
        return mType;
    }

    /**
     * TYPE_IMAGE设置 和 传入数据
     *
     * @param type
     * @param data
     * @param status
     */
    public void setTypeAndData(int type, ArrayList<Object> data, boolean status, int position, boolean isPicMode) {
        mType = type;
        mCheckStatus = status;
        mPosition = position;
        mPicMode = isPicMode;
        mListData = data;
        mSeparator = null;
        if (mType == TYPE_IMAGE && data != null) {
            int len = data.size();
            if (getChildCount() == 0) {
                for (int i = 0; i < len; ++i) {
                    setOrientation(HORIZONTAL);
                    GalleryCellItem item = new GalleryCellItem(getContext());
                    LinearLayout.LayoutParams params = new LayoutParams(mImageWidth, mImageWidth);
                    params.leftMargin = mMargin;
                    addView(item, params);
                    item.setOnItemListener(this);

                    if (i == len - 1) {//face tab: 最后一个为loading图标，开启动画
                        if (data.get(data.size() - 1) instanceof ThumbnailBean && ((ThumbnailBean) data.get(data.size() - 1)).getPath().equals("loading")) {
                            item.mLoadingImageView.setVisibility(VISIBLE);
                            loadingViewRotation(item.mLoadingImageView);
                        }
                    }
                }
            }
            for (int i = 0; i < getChildCount(); ++i) {
                GalleryCellItem item = (GalleryCellItem) getChildAt(i);
                if (i < len) {
                    item.setVisibility(VISIBLE);
                    item.updateData(data.get(i), isPicMode);
                } else {
                    item.setVisibility(INVISIBLE);
                }
            }
        }
    }

    private void loadingViewRotation(View view) {
        ObjectAnimator rotation = ObjectAnimator.ofFloat(view, "rotation", 0f, 359.9f);//最好是0f到359f，0f和360f的位置是重复的
        rotation.setRepeatCount(ObjectAnimator.INFINITE);
        rotation.setInterpolator(new LinearInterpolator());
        rotation.setDuration(1000);
        rotation.start();
    }

    /**
     * TYPE_SEPARATOR设置和传入数据
     *
     * @param type
     * @param data
     */
    public void setTypeAndData(int type, SeparatorBean data, boolean status, int position) {
        mType = type;
        mCheckStatus = status;
        mPosition = position;
        mSeparator = data;
        mListData = null;
        if (mType == TYPE_SEPARATOR) {
            if (data != null) {
                if (getChildCount() == 0) {
                    inflate(getContext(), R.layout.layout_gallery_separator, this);
                    mSeparatorTextView = findViewById(R.id.separator_text);
                    mSeparatorCheckBox = findViewById(R.id.separator_checkbox);
                    FontUtil.setCustomFontBold(mSeparatorTextView);
                    mSeparatorCheckBox.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onSeparatorCheckboxClick();
                        }
                    });
                }
                mSeparatorCheckBox.setSelected(data.isChecked());
                mSeparatorCheckBox.setVisibility(mCheckStatus ? VISIBLE : INVISIBLE);
                mSeparatorTextView.setText(data.getName());
            }
        }
    }

    public void updateItemStatus() {
        if (mSeparatorCheckBox != null && mSeparator != null) {
            mSeparatorCheckBox.setSelected(mSeparator.isChecked());
            mSeparatorCheckBox.setVisibility(mCheckStatus ? VISIBLE : INVISIBLE);
        }
        if (mListData != null) {
            int len = mListData.size();
            for (int i = 0; i < getChildCount(); ++i) {
                GalleryCellItem item = (GalleryCellItem) getChildAt(i);
                if (i < len) {
                    item.setVisibility(VISIBLE);
                    item.updateData(mListData.get(i), mPicMode);
                } else {
                    item.setVisibility(INVISIBLE);
                }
            }
        }
    }

    /**
     * 得到控件的高度
     *
     * @return
     */
    public int getItemHeight() {
        if (mType == TYPE_IMAGE) {
            return mImageWidth;
        } else if (mType == TYPE_SEPARATOR) {
            return mSeparatorHeight;
        } else {
            return 0;
        }
    }

    /**
     * 设置监听 用于回调点击和长按事件
     *
     * @param listener
     */
    public void setListener(OperationListener listener) {
        mListener = listener;
    }

    public abstract static class OperationListener {
        public abstract void OnClick(GalleryRowItem item, ThumbnailBean bean, int position);

        public abstract void OnLongClick(GalleryRowItem item, ThumbnailBean bean, int position);

        public abstract void OnCheckBoxClick(GalleryRowItem item, SeparatorBean bean, int position);

        public abstract void OnPlayVideoClick(GalleryRowItem item, ThumbnailBean bean, int position);

        public abstract void OnDown(GalleryRowItem item);

        public abstract void OnUp(GalleryRowItem item);
    }

    /**
     * 得到点击的Image的position
     *
     * @return
     */
    private int getOperationPosition(ThumbnailBean bean) {
        int ret = DO_NONE;
        for (int i = 0; i < getChildCount(); ++i) {
            View child = getChildAt(i);
            if (child instanceof GalleryCellItem) {
                Object data = ((GalleryCellItem) child).getData();
                if (data == bean) {
                    ret = i;
                    break;
                }
            }
        }
        return ret;
    }

    public void setCheckStatus(boolean checkStatus) {
        mCheckStatus = checkStatus;
    }

    public boolean isCheckStatus() {
        return mCheckStatus;
    }

    @Override
    public void onPlayClick(GalleryCellItem view, ThumbnailBean bean) {
        if (mType == TYPE_IMAGE) {
            if (mCheckStatus) {//如果是选中状态
                if (mListener != null) {
                    mListener.OnClick(GalleryRowItem.this, bean, mPosition);
                }
            } else {//非选中
                if (mListener != null) {
                    mListener.OnPlayVideoClick(GalleryRowItem.this, bean, mPosition);
                }
            }
        }
    }

    private void onSeparatorCheckboxClick() {
        if (mListener != null) {
            mListener.OnCheckBoxClick(GalleryRowItem.this, mSeparator, mPosition);
        }
    }

    @Override
    public void onImageClick(GalleryCellItem view, ThumbnailBean bean) {
        if (mType == TYPE_IMAGE) {
            if (mListener != null) {
                mListener.OnClick(GalleryRowItem.this, bean, mPosition);
            }
        }
    }

    @Override
    public void onDown(GalleryCellItem view, ThumbnailBean bean) {
        if (mListener != null) {
            mListener.OnDown(GalleryRowItem.this);
        }
    }

    @Override
    public void onUp(GalleryCellItem view, ThumbnailBean bean) {
        if (mListener != null) {
            mListener.OnUp(GalleryRowItem.this);
        }
    }

    @Override
    public void onImageLongClick(GalleryCellItem view, ThumbnailBean bean) {
        if (mType == TYPE_IMAGE) {
            int position = getOperationPosition(bean);
            if (position != DO_NONE) {
                if (mListener != null) {
                    mListener.OnLongClick(GalleryRowItem.this, bean, mPosition);
                }
            }
        }
    }

    public RectF getThumbRect(ThumbnailBean bean) {
        if (mType == TYPE_IMAGE) {
            for (int i = 0; i < getChildCount(); ++i) {
                View child = getChildAt(i);
                if (child instanceof GalleryCellItem) {
                    Object data = ((GalleryCellItem) child).getData();
                    if (data == bean) {
                        return new RectF(child.getLeft(), 0, child.getRight(), getBottom());
                    }
                }
            }
        }
        return new RectF();
    }

    public Bitmap getThumbBitmap(ThumbnailBean bean) {
        if (mType == TYPE_IMAGE) {
            for (int i = 0; i < getChildCount(); ++i) {
                View child = getChildAt(i);
                if (child instanceof GalleryCellItem) {
                    Object data = ((GalleryCellItem) child).getData();
                    if (data == bean) {
                        Bitmap bitmap = ((GalleryCellItem) child).getThumbnail();
                        if (bitmap != null) {
                            return bitmap;
                        }
                        break;
                    }
                }
            }
            BitmapBean bitmapBean = ImageHelper.toBitmapBean(bean);
            ImageHelper.UriToBitmap(bitmapBean);
        }
        return null;
    }
}
